//
//  ProductAllEditVC.m
//  LazyCat
//
//  Created by jike on 16/9/26.
//  Copyright © 2016年 zhanshu. All rights reserved.
//

#import "ProductAllEditVC.h"
#import "MJChiBaoZiHeader.h"
#import "MJChiBaoZiFooter.h"
#import "WebViewController.h"
#import "EditButton.h"
#import "FeWifiManHub.h"
#import "ProductManagerVC.h"
#import "ProductSeleCell.h"
@interface ProductAllEditVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong)UITableView *tableView;

@property (nonatomic, strong)UIView *bottomViewEdit;

@property (nonatomic, strong)UIImageView *seleImageView;

@property (nonatomic, strong)NSMutableArray * editSeleArr;

@property (nonatomic, strong)NSMutableArray *editDataArr;
@end

@implementation ProductAllEditVC
{
    NSMutableArray * _dataArray;
    UIView *_backTView;//没订单时背部提醒
    NSString * _urlIndex;//起始页
    BOOL _isLoading;
    NSString *_totalCount;//总页数
    NSDictionary *dataDic;
    NSString *_moneyStr;//成本全局变量
    NSString *_proID;//产品ID
    NSString *_isHot;//是否为推荐
    UITextField *_textField1;//编辑库存
    UIView *popView;
    UIView *_timeView;//库存编辑view
    int _keyH;//键盘高度
    NSString *_proName;//名字
    NSString *_proImg;
    NSIndexPath *_indexPath;//编辑库存刷新指定一行
    FeWifiManHub *_loading;
    NSString *_str;
    NSArray *_editArr;//改变的数据源
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    [self loadData:nil];
    [AppData share].isLoadd = NO;
    self.tableView.header = [MJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(addRefresh)];
}

- (void)createUI {
    [self initNav:@"商品批量管理" doBack:YES];
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 64 - 50) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
//    self.tableView.editing = YES;
    self.tableView.backgroundColor = BackColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.tableView];
    _backTView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 64 - 50)];
    _backTView.backgroundColor = BackColor;
    _backTView.hidden = YES;
    [self.view addSubview:_backTView];
    UIImageView *backImage = [[UIImageView alloc]initWithFrame:CGRectMake((ScreenWidth - 80)/2, 100, 80, 90)];
    backImage.image = [UIImage imageNamed:@"chanpin-no"];
    [_backTView addSubview:backImage];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake((ScreenWidth - 200)/2, backImage.frame.origin.y + 90, 200, 50)];
    label.textColor = SetColor(153, 153, 153, 1);
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"抱歉,您暂时还没有产品";
    [_backTView addSubview:label];
    _urlIndex = @"1";
    _loading = [[FeWifiManHub alloc] initWithView:self.tableView withMode:FeWifiManHubModeOnlyLoader];
    _loading.frame = CGRectMake(_loading.frame.origin.x, _loading.frame.origin.y - 104, _loading.frame.size.width, _loading.frame.size.height);
    [self.tableView addSubview:_loading];
    [_loading show];
    _dataArray = [[NSMutableArray alloc]init];
    _isLoading = NO;
    MJRefreshAutoFooter *foot = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    self.tableView.footer = foot;
    [self createBottomView];
}

- (void)createBottomView
{
    /*
     bottomViewTwo
     
     */
    self.bottomViewEdit = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight - 50, ScreenWidth, 50)];
    self.bottomViewEdit.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bottomViewEdit];
    
    //leftView
    self.seleImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 16, 17, 17)];
    self.seleImageView.image = [UIImage imageNamed:@"btn_delete"];
    [self.bottomViewEdit addSubview:self.seleImageView];
    
    UILabel *allSeleLabel = [[UILabel alloc]initWithFrame:CGRectMake(37, 0, 63, 50)];
    allSeleLabel.font = FontSet(13);
    allSeleLabel.textAlignment = NSTextAlignmentLeft;
    allSeleLabel.text = @"全选";
    allSeleLabel.textColor = SetColor(51, 51, 51, 1);
    [self.bottomViewEdit addSubview:allSeleLabel];
    
    // bottomBtn
    NSString *titleStr;
    if (self.currentPage == 0) {
        titleStr = @"全部下架";
    }else {
        titleStr = @"全部上架";
    }
    NSArray *btnArr = @[@"",titleStr];
    CGFloat height = 40;
    CGFloat space = 10;
    CGFloat width = (ScreenWidth - (space * 3)) / 2.0;
    for (int i = 0; i < btnArr.count; i++) {
        UIButton *bottomBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        bottomBtn.frame = CGRectMake(space + i * (width + space), 5, 100 + i * (width - 100), height);
        [bottomBtn setTitle:btnArr[i] forState:UIControlStateNormal];
        [bottomBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [bottomBtn setBackgroundColor:i == 0 ? [UIColor clearColor] : SetColor(204, 204, 204, 1)];
        bottomBtn.titleLabel.font = FontSet(16);
        bottomBtn.layer.cornerRadius = 5;
        bottomBtn.layer.masksToBounds = YES;
        [bottomBtn addTarget:self action:@selector(bottomBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        bottomBtn.tag = 17 + i;
        [self.bottomViewEdit addSubview:bottomBtn];
    }
}

- (void)loadData:(NSIndexPath *)indexPath {
    NSString *kUrl;
    if(self.currentPage == 0){
        kUrl = [NSString stringWithFormat:productManagerUrl,@"15",_urlIndex,[AppData share].username,@"1",[AppData share].username,self.isHotVC,@""];
    }else if(self.currentPage == 1){
        kUrl = [NSString stringWithFormat:productManagerUrl,@"15",_urlIndex,[AppData share].username,@"0",[AppData share].username,self.isHotVC,@""];
    }
    if ([_urlIndex isEqualToString:@"1"]) {
        [_dataArray removeAllObjects];
        [self.editSeleArr removeAllObjects];
    }
    [NTNetUtil sendRequestWithUrl:kUrl requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
        NSDictionary *dic = networkRequest.responseData;
        _totalCount = [dic objectForKey:@"totalpage"];
        NSArray *arr = [dic objectForKey:@"products"];
        _editArr = arr;
        [_dataArray addObjectsFromArray:arr];
        
        // 选择判断数组
        NSMutableArray *editArr = [NSMutableArray array];
        for (int i = 0; i < arr.count; i++) {
            [editArr addObject:@"0"];
        }
        [self.editSeleArr addObjectsFromArray:editArr];
        NSLog(@"editArr:%@",self.editSeleArr);
        
        _isLoading = NO;
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        if ([_totalCount isEqualToString:@"0"] || _totalCount == nil) {
            _backTView.hidden = NO;
        }else {
            _backTView.hidden = YES;
        }
        [_loading dismiss];
        [_loading removeFromSuperview];
        [self.tableView reloadData];
    }];
    if (kNetworkNotReachability) {
        [_loading dismiss];
        [_loading removeFromSuperview];
    }
}

//*----------/////
- (void)loadDataaaa:(NSIndexPath *)indexPath {
    NSString *kUrl;
    NSString *numCount;//数据量
    NSInteger count = ([_urlIndex integerValue] - 1) * 15 +_editArr.count;//数据量
    numCount = [NSString stringWithFormat:@"%ld",count];
    
    if(self.currentPage == 0){
        kUrl = [NSString stringWithFormat:productManagerUrl,numCount,@"1",[AppData share].username,@"1",[AppData share].username,self.isHotVC,@""];
    }else if(self.currentPage == 1){
        kUrl = [NSString stringWithFormat:productManagerUrl,numCount,@"1",[AppData share].username,@"0",[AppData share].username,self.isHotVC,@""];
    }
    
    [_dataArray removeAllObjects];
    [NTNetUtil sendRequestWithUrl:kUrl requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
        NSDictionary *dic = networkRequest.responseData;
        _totalCount = [dic objectForKey:@"totalpage"];
        NSArray *arr = [dic objectForKey:@"products"];
        [_dataArray addObjectsFromArray:arr];
        [self.tableView reloadData];
    }];
}

- (void)addRefresh {
    if (_isLoading) {
        return;
    }
    _isLoading = YES;
    _urlIndex = @"1";
    [self loadData:nil];
    [self.tableView.header endRefreshing];
}
- (void)loadMore {
    if (_isLoading) {
        return;
    }
    _isLoading = YES;
    if ([_urlIndex integerValue] >= [_totalCount integerValue]) {
        [[MessShowView share]showWithMess:@"没有更多数据"];
        return ;
    }else{
        _urlIndex = [NSString stringWithFormat:@"%ld",[_urlIndex integerValue]+1];
        [self loadData:nil];
    }
}
- (void)loadDataBBBBB:(NSIndexPath *)indexPath {
    NSString *kUrl;
    if(self.currentPage == 0){
        kUrl = [NSString stringWithFormat:productManagerUrl,@"1",[NSString stringWithFormat:@"%ld",indexPath.row+1],[AppData share].username,@"",@"1"];
    }else if(self.currentPage == 1){
        kUrl = [NSString stringWithFormat:productManagerUrl,@"1",[NSString stringWithFormat:@"%ld",indexPath.row+1],[AppData share].username,@"",@"0"];
    }
    [NTNetUtil sendRequestWithUrl:kUrl requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
        NSDictionary *dic = networkRequest.responseData;
        _totalCount = [dic objectForKey:@"totalpage"];
        NSArray *arr = [dic objectForKey:@"products"];
        [_dataArray replaceObjectAtIndex:indexPath.row withObject:[arr firstObject]];
        [self.tableView reloadData];
    }];
}

#pragma mark -- cell上按钮点击方法
- (void)btnClick:(UIButton *)sender event:(id)event {
    //取indexpath
    NSSet *touches =[event allTouches];
    UITouch *touch =[touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tableView];
    NSIndexPath *indexPath= [self.tableView indexPathForRowAtPoint:currentTouchPosition];
    _indexPath = indexPath;
    if (indexPath!= nil)
    {
        NSLog(@"我在第%ld行，编号%ld",(long)indexPath.row,(long)sender.tag);
        if (sender.tag == 1110) {//上架
         
#pragma mark -- menu..编辑菜单
        }else if (sender.tag == 1114){//编辑菜单menu

        }else if (sender.tag == 60){ // 单选按钮
            
            if (indexPath.row < self.editSeleArr.count) {
                if ([self.editSeleArr[indexPath.row] isEqualToString:@"1"])
                {
                    [self.editSeleArr replaceObjectAtIndex:indexPath.row withObject:@"0"];
                }else {
                    [self.editSeleArr replaceObjectAtIndex:indexPath.row withObject:@"1"];
                }
            }
            // 全部上下架按钮状态
            [self allSoldOutBtnShow];
            
            //刷新某一行
            NSIndexPath *refreshIndexPath=[NSIndexPath indexPathForRow:indexPath.row inSection:0];
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:refreshIndexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        }
    }
}

#pragma mark - TableView data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ProductSeleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"productselecell"];
    if (cell == nil) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"ProductSeleCell" owner:nil options:nil][0];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.baoCunBtn.hidden = YES;
    [cell.selecteBtn addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];

    cell.backgroundColor = [UIColor whiteColor];
    
    // 选择按钮显示
    if (indexPath.row < [self.editSeleArr count]) {
        if ([self.editSeleArr[indexPath.row] isEqualToString:@"1"]) {
            cell.selecteImageV.image = [UIImage imageNamed:@"btn_choice"];
        }else
        {
            cell.selecteImageV.image = [UIImage imageNamed:@"btn_delete"];
        }
    }

    //产品数组
    if (indexPath.row < [_dataArray count]) {////////防止数组越界
        
        cell.titleLabel.text = [_dataArray[indexPath.row]objectForKey:@"productname"];
        cell.kuCunLabel.text = [NSString stringWithFormat:@"%@",[_dataArray[indexPath.row]objectForKey:@"totalnumstock"]];//库存
        cell.kuCunLabel.adjustsFontSizeToFitWidth = YES;
        cell.shouJiaTextF.text = [_dataArray[indexPath.row]objectForKey:@"minsaleprice"];//价格
        //售价输入框
        cell.shouJiaTextF.textColor = MainColor;
        cell.shouJiaTextF.font = [UIFont systemFontOfSize:17];
        cell.shouJiaTextF.tag = 2222;
        cell.shouJiaTextF.autocorrectionType = UITextAutocorrectionTypeNo;
        
        cell.shouJiaTextF.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        //成本价输入框
        cell.chengBenTextF.text = [_dataArray[indexPath.row]objectForKey:@"mincostprice"];
        cell.chengBenTextF.font = [UIFont systemFontOfSize:12];
        [cell.iconImage sd_setImageWithURL:[NSURL URLWithString:[_dataArray[indexPath.row]objectForKey:@"mainimage"]] placeholderImage:[UIImage imageNamed:@"product-no-pic"]];
        cell.chengBenTextF.adjustsFontSizeToFitWidth = YES;
        cell.chengBenTextF.tag = 2223;
        cell.chengBenTextF.autocorrectionType = UITextAutocorrectionTypeNo;
        cell.chengBenTextF.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        [cell.chengBenTextF setValue:[UIFont boldSystemFontOfSize:11] forKeyPath:@"_placeholderLabel.font"];
        
        // 多规格  property specname
        NSString *tagTitle = [_dataArray[indexPath.row]objectForKey:@"title"];
        if (tagTitle.length != 0) {
            cell.tagTitle.hidden = NO;
        }else {
            cell.tagTitle.hidden = YES;
        }
        cell.guigeLabel.text = [_dataArray[indexPath.row]objectForKey:@"specname"];
    }
    [cell.subviews[0] setBackgroundColor:[UIColor clearColor]];
    [cell setNeedsDisplay];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 110;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

// 全部上下架按钮状态
- (void)allSoldOutBtnShow
{
    UIButton *allSeleBtn = (UIButton *)[self.view viewWithTag:17];
    UIButton *allSoldOutBtn = (UIButton *)[self.view viewWithTag:18];
    
    int countNum = 0;
    if (self.editSeleArr.count > 0)
    {
        for (int i = 0; i < self.editSeleArr.count; i++) {
            NSString *selectedValue = (NSString *)self.editSeleArr[i];
            if ([selectedValue isEqualToString:@"1"]) {
                countNum++;
            }
        }
        
        if (countNum > 0) {
            allSoldOutBtn.backgroundColor = MainColor;
            allSoldOutBtn.enabled = YES;
            if (countNum == self.editSeleArr.count)
            {
                allSeleBtn.selected = YES;
                self.seleImageView.image = [UIImage imageNamed:@"btn_choice"];
            }else
            {
                allSeleBtn.selected = NO;
                self.seleImageView.image = [UIImage imageNamed:@"btn_delete"];
            }
        }else {
            allSoldOutBtn.backgroundColor = SetColor(204, 204, 204, 1);
            allSoldOutBtn.enabled = NO;
        }
    }
}
#pragma mark -- Clicked..
//bottomView两个按钮点击事件 (tag == 17,18)
- (void)bottomBtnClicked:(UIButton *)sender
{
    if (sender.tag == 17){ // 全选
        if (!sender.isSelected) { // 全选
            self.seleImageView.image = [UIImage imageNamed:@"btn_choice"];
            sender.selected = YES;
            
            for (int i = 0; i < self.editSeleArr.count; i ++)
            {
                [self.editSeleArr replaceObjectAtIndex:i withObject:@"1"];
            }
            
        }else { //取消全选
            sender.selected = NO;
            self.seleImageView.image = [UIImage imageNamed:@"btn_delete"];
            for (int i = 0; i < self.editSeleArr.count; i ++)
            {
                [self.editSeleArr replaceObjectAtIndex:i withObject:@"0"];
            }
        }
        // 全部上下架按钮状态
        [self allSoldOutBtnShow];
        
        [self.tableView reloadData];
    }
#pragma mark -- 全部上下架
    else if (sender.tag == 18){ // 全部上下架
        NSLog(@"全部上架");
        NSMutableArray *seleArr = [[NSMutableArray alloc]init];
        if (self.editSeleArr.count > 0)
        {
            for (int i = 0; i < self.editSeleArr.count; i++) {
                NSString *selectedValue = (NSString *)self.editSeleArr[i];
                if ([selectedValue isEqualToString:@"1"])
                {
                    [seleArr addObject:_dataArray[i]];
                }
            }
        }
        
        NSMutableArray *arr = [NSMutableArray array];//产品信息
        for (int i = 0; i < seleArr.count; i++)
        {
            NSString *proID = [seleArr[i] objectForKey:@"productid"];
            [arr addObject:proID];
        }
        
        NSString *kUrl;
        NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
        
        NSString *ispublic = [NSString stringWithFormat:@"%@",self.currentPage == 0 ? @"0" : @"1"];
        
        [dictionary setValue:arr forKey:@"productids"];
        [dictionary setValue:ispublic forKey:@"ispublic"];
        NSLog(@"%@",dictionary);
        NSError *error = nil;
        //NSJSONWritingPrettyPrinted:指定生成的JSON数据应使用空格旨在使输出更加可读。如果这个选项是没有设置,最紧凑的可能生成JSON表示。
        NSData *jsonData = [NSJSONSerialization
                            dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
        if ([jsonData length] > 0 && error == nil){
            NSLog(@"Successfully serialized the dictionary into data.");
            //NSData转换为String
            NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            NSLog(@"JSON String = %@", jsonString);
        }
        else if ([jsonData length] == 0 &&
                 error == nil){
            NSLog(@"No data was returned after serialization.");
        }
        else if (error != nil){
            NSLog(@"An error happened = %@", error);
        }
        //post请求
        kUrl = [NSString stringWithFormat:shangXiaJiaProduct,[AppData share].username,[AppData share].username];
        NSLog(@"%@",kUrl);
        NSMutableDictionary *dicc = [NSMutableDictionary dictionary];
        [dicc setObject:dictionary forKey:@"data"];
        NSLog(@"%@",dicc);
        // 手机型号
        NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults];
        NSString *iptype = [userDefaul objectForKey:@"iptype"];
        NSString *banben = [userDefaul objectForKey:@"banben"];
        NSString *temUrl = [NSString stringWithFormat:@"%@&terminal=%@&OSVersion=%@",kUrl,iptype,banben];
        // 判断是否签名
        if([temUrl rangeOfString:@"sign2"].location !=NSNotFound)//_roaldSearchText
        {
            // 存在
        }else{
            // 不存在
            temUrl = [NSString stringWithFormat:@"%@&sign2=%@",temUrl,[Utils md5SignStr]];
            
        }
        NSString *lower = [temUrl lowercaseString];
        if ([lower rangeOfString:@"username"].location !=NSNotFound) {
            // 存在
        }else{
            // 不存在
            temUrl = [NSString stringWithFormat:@"%@&Username=%@",temUrl,[AppData share].username];
        }
        //NSLog(@"1----------%@",temUrl);
        temUrl = [temUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        //NSLog(@"2----------%@",temUrl);
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSError *error1;
        NSURLResponse *theResponse;
        NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:temUrl]];
        NSString *bodyString=[NSString stringWithFormat:@"data=%@",jsonString];
        [theRequest setHTTPMethod:@"POST"];
        [theRequest setHTTPBody:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];
        [theRequest addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        NSData *data = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&error];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if ([dic[@"r"] isEqualToString:@"T"]) {
            [[MessShowView share]showWithMess:[NSString stringWithFormat:@"%@",self.currentPage == 0 ? @"下架成功" : @"上架成功"]];
            
            for (int i = 0; i < self.editSeleArr.count; i++)
            {
                [self.editSeleArr replaceObjectAtIndex:i withObject:@"0"];
            }
            
            if (_indexPath.row < [_dataArray count]) {
                [self loadDataaaa:nil];
            }
            [AppData share].isLoadd = YES;//改变刷新
            
            [self allSoldOutBtnShow];
            
        }else {
            [[MessShowView share]showWithMess:dic[@"m"]];
        }
    }
}

#pragma mark -- lazying
- (NSMutableArray *)editSeleArr {
    if (!_editSeleArr) {
        _editSeleArr = [[NSMutableArray alloc] init];
    }
    return _editSeleArr;
}

- (NSMutableArray *)editDataArr {
    if (!_editDataArr) {
        _editDataArr = [[NSMutableArray alloc] init];
    }
    return _editDataArr;
}
@end
